#!/bin/bash

# ProductAnyShoot任务监测定时任务设置脚本

PROJECT_PATH="/Users/liubb/wwwroot/wwwroot/ai"
LOG_PATH="/var/log/product_anyshoot_tasks.log"

echo "=== ProductAnyShoot任务监测定时任务设置 ==="
echo "项目路径: $PROJECT_PATH"
echo "日志路径: $LOG_PATH"
echo ""

# 检查项目路径是否存在
if [ ! -d "$PROJECT_PATH" ]; then
    echo "错误: 项目路径不存在: $PROJECT_PATH"
    exit 1
fi

# 检查命令是否可用
cd "$PROJECT_PATH"
if ! php think check:product-anyshoot-tasks --help > /dev/null 2>&1; then
    echo "错误: 命令不可用，请检查项目配置"
    exit 1
fi

echo "选择定时任务频率:"
echo "1) 每2分钟检查一次 (高频率)"
echo "2) 每5分钟检查一次 (推荐)"
echo "3) 每10分钟检查一次 (低频率)"
echo "4) 查看当前crontab配置"
echo "5) 删除相关crontab配置"
echo "6) 手动执行一次检查"
echo ""

read -p "请选择 (1-6): " choice

case $choice in
    1)
        CRON_SCHEDULE="*/2 * * * *"
        ;;
    2)
        CRON_SCHEDULE="*/5 * * * *"
        ;;
    3)
        CRON_SCHEDULE="*/10 * * * *"
        ;;
    4)
        echo "当前crontab配置:"
        crontab -l | grep "product-anyshoot-tasks" || echo "未找到相关配置"
        exit 0
        ;;
    5)
        echo "删除相关crontab配置..."
        crontab -l | grep -v "product-anyshoot-tasks" | crontab -
        echo "删除完成"
        exit 0
        ;;
    6)
        echo "手动执行任务检查..."
        cd "$PROJECT_PATH" && php think check:product-anyshoot-tasks
        exit 0
        ;;
    *)
        echo "无效选择"
        exit 1
        ;;
esac

# 构建cron任务
CRON_JOB="$CRON_SCHEDULE cd $PROJECT_PATH && php think check:product-anyshoot-tasks >> $LOG_PATH 2>&1"

echo "将添加以下cron任务:"
echo "$CRON_JOB"
echo ""

read -p "确认添加? (y/N): " confirm
if [[ $confirm != [yY] ]]; then
    echo "取消操作"
    exit 0
fi

# 备份当前crontab
echo "备份当前crontab..."
crontab -l > /tmp/crontab_backup_$(date +%Y%m%d_%H%M%S) 2>/dev/null || true

# 删除旧的相关配置
echo "删除旧的相关配置..."
crontab -l 2>/dev/null | grep -v "product-anyshoot-tasks" | crontab - 2>/dev/null || true

# 添加新配置
echo "添加新的cron任务..."
(crontab -l 2>/dev/null; echo "$CRON_JOB") | crontab -

echo "设置完成！"
echo ""
echo "验证配置:"
crontab -l | grep "product-anyshoot-tasks"
echo ""
echo "日志查看命令:"
echo "tail -f $LOG_PATH"
echo ""
echo "手动执行命令:"
echo "cd $PROJECT_PATH && php think check:product-anyshoot-tasks" 